package de.mariusharbeck.saralentz.web.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.mariusharbeck.saralentz.entity.Bild;
import de.mariusharbeck.saralentz.service.BildService;
import de.mariusharbeck.saralentz.service.impl.BildServiceImpl;

/**
 * Servlet implementation class ShowImage
 */
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int DEFAULT_BUFFER_SIZE = 10240;

	private BildService bildDB;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ImageServlet() {
		super();
		bildDB = new BildServiceImpl();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String type = request.getParameter("type");
		int bid = Integer.parseInt(request.getParameter("bid"));
		Bild bild = bildDB.findBild(bid);

		if (bild == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		String mT = getServletContext().getMimeType(bild.getFormat());
		response.setContentType(mT);
		response.setBufferSize(DEFAULT_BUFFER_SIZE);
		if ("thumb".equals(type)) {
			response.setContentLength((int) bild.getThumbSize());
			response.getOutputStream().write(bild.getThumb());
			return;
		} else if ("normal".equals(type)) {
			response.setContentLength((int) bild.getImageSize());
			response.getOutputStream().write(bild.getImage());
			bildDB.addHit(bid);
			return;
		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		doGet(request, response);
	}

}
